package cn.oatn;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class T1007_ASM_AddMethod {

    public static void test() throws IOException {
        ClassReader cr = new ClassReader("cn.oatn.MyRunnable");
        ClassWriter cw = new ClassWriter(0);

        cr.accept(new ClassVisitor(Opcodes.ASM9, cw) {
            @Override
            public void visitEnd() {
                MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "b", "()V", null, null);
                // 下面这段直接对应代码System.out.println("b");
                mv.visitCode();
                mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
                mv.visitLdcInsn("b");
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/Object;)V", false);
                mv.visitInsn(Opcodes.RETURN);

                // 然后是Maxs和End
                mv.visitMaxs(2, 1);
                mv.visitEnd();

                super.visitEnd();
            }
        }, 0);

        OutputStream o = new FileOutputStream("XXX.class");
        o.write(cw.toByteArray());
        o.close();

    }

}
